package top.infopub.mgr.bpa.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.enums.bpa.BpaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.bpa.dao.*;
import top.infopub.mgr.bpa.domain.BpaProjectDomain;
import top.infopub.mgr.bpa.domain.InnerAgrtDomain;
import top.infopub.mgr.bpa.domain.InnerLedgerDomain;
import top.infopub.mgr.bpa.jsonVo.InnerAgrtJsonVo;
import top.infopub.mgr.bpa.service.BpaProcessManageService;
import top.infopub.mgr.bpa.service.InnerAgrtService;
import top.infopub.mgr.bpa.vo.ContractManageVo;
import top.infopub.mgr.bpa.vo.InnerAgrtVo;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.service.WsFlowProcessService;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.model.bpa.BpaCompPlan;
import top.infopub.model.bpa.InnerAgrt;
import top.infopub.model.bpa.InnerAgrtSup;
import top.infopub.model.bpa.InnerListing;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

@Service
public class InnerAgrtServiceImpl extends GenericServiceImpl<InnerAgrt, String> implements
		InnerAgrtService {

	@Autowired
	private InnerAgrtDao innerAgrtDao;
	@Autowired
	private ProjectAttachmentDao projectAttachmentDao;

	@Autowired
	private BpaProcessManageService bpaProcessManageService;

	@Override
	public GenericDao<InnerAgrt, String> getDao() {
		return innerAgrtDao;
	}

    @Override
    public Page<InnerAgrtDomain> selectByDomainWhere(Page<InnerAgrtDomain> page,
                                                     InnerAgrtVo innerAgrtVo) throws ParseException {
        //处理时间范围
        if (!StringUtils.isEmpty(innerAgrtVo.getDates()))
        {
            String[] splitTime = innerAgrtVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            innerAgrtVo.setStartDate(format.parse(splitTime[0]));
            innerAgrtVo.setEndDate(format.parse(splitTime[1]));
        }
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<InnerAgrtDomain>)innerAgrtDao.selectByDomainWhere(innerAgrtVo);
    }

	@Override
	public Page<InnerLedgerDomain> selectByLedger(Page<InnerLedgerDomain> page, ContractManageVo contractManageVo) throws ParseException {
		//处理时间范围
		if (!StringUtils.isEmpty(contractManageVo.getDates()))
		{
			String[] splitTime = contractManageVo.getDates().split("~");
			SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
			contractManageVo.setStartDate(format.parse(splitTime[0]));
			contractManageVo.setEndDate(format.parse(splitTime[1]));
		}
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		return (Page<InnerLedgerDomain>)innerAgrtDao.selectByLedger(contractManageVo);
	}

	@Override
	public RspVo selectProject() {
	 List<BpaProjectDomain> bpaProjectDomain = innerAgrtDao.selectProject();
		return RspVo.getSuccessResponse(bpaProjectDomain);
	}

	@Override
	public RspVo queryById(String id) {
		InnerAgrtJsonVo jsonVo = new InnerAgrtJsonVo();
		//主表信息
		InnerAgrt innerAgrt = innerAgrtDao.selectByPrimaryKey(id);
		//合同评审信息
		InnerAgrtSup innerAgrtSup = innerAgrtDao.selectSup(innerAgrt.getId(),"1");
		//子项信息---待定
		List<InnerListing> innerListings = innerAgrtDao.selectListing(id,"1");
		//综合计划
		List<BpaCompPlan> compPlan = innerAgrtDao.selectPlan(innerAgrt.getId(),"1");
		//附件信息
		List<ProjectAttachment> attachmentList = projectAttachmentDao.queryByWhere(innerAgrt.getProCode(), ProjectFileTypeEnum.FILE_TYPE79.getCode(), null);
		jsonVo.setInnerAgrt(innerAgrt);
		jsonVo.setInnerAgrtSup(innerAgrtSup);
		jsonVo.setCompPlan(compPlan);
		jsonVo.setInnerListings(innerListings);
		jsonVo.setFileAtt(fileAttaListToArray(attachmentList));
		return  RspVo.getSuccessResponse(jsonVo);
	}

	@Override
	@Transactional
	public RspVo saveAll(Integer submitType, AuthorizationVO userDtl, InnerAgrt innerAgrt, List<InnerListing> innerListings, InnerAgrtSup innerAgrtSup, List<BpaCompPlan> compPlan, List<ProjectAttachment> attachmentList,String bodyStr) {
		//处理主表数据
		if (StringUtils.isNotBlank(innerAgrt.getId())){
			innerAgrtDao.updateByPrimaryKey(innerAgrt);
		}else{
			//查询是否已发起过内部协议
			InnerAgrt inner= innerAgrtDao.selectByProCodes(innerAgrt.getProCode());
			if (inner!=null){
				return RspVo.getFailureResponse(401,"该项目已发起过内部协议");
			}
			innerAgrtDao.insertById(innerAgrt);
		}
		final String type = "1"; //合同评审
		//处理合同评审详细信息
		innerAgrtDao.deleteAgrtSup(innerAgrt.getId(),type);
		innerAgrtSup.setId(IdFactory.getUUIDUpper());
		innerAgrtSup.setInnerId(innerAgrt.getId());
		innerAgrtSup.setInnerType("1");
		innerAgrtDao.insertAgrtSup(innerAgrtSup);

		//处理子项信息
		innerAgrtDao.deleteListing(innerAgrt.getId(),type);
		int seq = 0;
		for (InnerListing innerListing : innerListings) {
			innerListing.setInnerId(innerAgrt.getId());
			innerListing.setType("1");
			innerListing.setSeq(seq++);
		}
		innerAgrtDao.insertBatchListing(innerListings);
		//处理综合计划
		innerAgrtDao.deletePlan(innerAgrt.getId(),type);
		for (BpaCompPlan bpaCompPlan : compPlan) {
			bpaCompPlan.setContractId(innerAgrt.getId());
			bpaCompPlan.setType("1");
		}
		innerAgrtDao.insertBatchPlan(compPlan);

		//处理附件
		if (attachmentList!=null && attachmentList.size()>0){
			//批量插入附件信息
			projectAttachmentDao.deleteByWhere(innerAgrt.getProCode(), ProjectFileTypeEnum.FILE_TYPE79.getCode(), null);
			for (ProjectAttachment attachment : attachmentList) {
				attachment.setProCode(innerAgrt.getProCode());
			}
			projectAttachmentDao.insertBatch(attachmentList);
		}
		if (submitType==2){
			bpaProcessManageService.sendProcess(BpaProcessDetailTypeEnum.PRO_NODE_TYPE7, bodyStr, innerAgrt.getId(), innerAgrt.getProCode(), userDtl);
		}
		return RspVo.getSuccessResponse();
	}

	@Override
	public InnerAgrt selectBySguid(String id) {
		return innerAgrtDao.selectByPrimaryKey(id);
	}


	public String[] fileAttaListToArray(List<ProjectAttachment> list) {
		if (list == null || list.size() <= 0) return null;
		String[] attaArr = new String[list.size()];
		int index = 0;
		for (ProjectAttachment pa : list) {
			StringBuffer tmp = new StringBuffer();
			tmp.append(pa.getSubTypes());
			tmp.append("|");
			tmp.append(pa.getFileName());
			tmp.append(pa.getFileSuffix());
			tmp.append("|");
			tmp.append(IdFactory.getUUIDSerialNumber());
			tmp.append("|");
			tmp.append(pa.getFilePath());
			attaArr[index] = tmp.toString();
			index++;
		}
		return attaArr;
	}
//    @Override
//    public Page<InnerAgrtDomain> selectMyCheckByDomainWhere(Page<InnerAgrtDomain> page,
//                                                            InnerAgrtVo innerAgrtVo) {
//        PageHelper.startPage(page.getPageNum(), page.getPageSize());
//        return (Page<InnerAgrtDomain>)innerAgrtDao.selectMyCheckByDomainWhere(innerAgrtVo);
//    }
//
//    @Override
//    public List<InnerAgrt> isExistInnerAgrtName(String InnerAgrtName,String proCode) {
//        return innerAgrtDao.isExistInnerAgrtName(InnerAgrtName,proCode);
//    }
//
//    @Override
//    @Transactional(rollbackFor=Exception.class)
//    public void saveInnerAgrt(InnerAgrt innerAgrt,
//                              List<InnerAgrtSub> innerAgrtSubs,
//                              List<InnerAgrtDetail> innerAgrtDetails,
//                              List<InnerAgrtRate> innerAgrtRates, List<InnerAgrtAtt> innerAgrtAtts) {
//        //添加主表信息
//        innerAgrtDao.insertById(innerAgrt);
//
//        //添加内部协议对应月度付款比例
//        if(CollectionUtils.isNotEmpty(innerAgrtRates)){
//            innerAgrtRateDao.insertByBatch(innerAgrtRates);
//        }
//
//        //添加内部协议清单分解子项
//        if(CollectionUtils.isNotEmpty(innerAgrtSubs)){
//            innerAgrtSubDao.insertByBatch(innerAgrtSubs);
//        }
//
//        //添加内部协议清单分解子项费用明细
//        if(CollectionUtils.isNotEmpty(innerAgrtDetails)){
//            innerAgrtDetailDao.insertByBatch(innerAgrtDetails);
//        }
//
//        //添加附件
//        if(CollectionUtils.isNotEmpty(innerAgrtAtts)){
//            innerAgrtAttDao.insertByBatch(innerAgrtAtts);
//        }
//
//        // 注意 这里根据不同的业务分支判断条件 获得不同enum
//        FlowTemplateEnum templateEnum = FlowTemplateEnum.BPA_INNER_AGRT;
//        // 处理工作流数据
//        wsFlowProcess.launch(templateEnum, innerAgrt.getId(), innerAgrt.getProcessId(), null);
//
//    }
//
//    @Override
//    public List<InnerAgrt> isExistInnerAgrtSaName(String innerAgrtSaName,String proCode) {
//        return innerAgrtDao.isExistInnerAgrtSaName(innerAgrtSaName,proCode);
//    }
//
//    @Override
//    public List<InnerAgrt> selectVersionNoByProCode(String proCode,String status,String extType) {
//        return innerAgrtDao.selectVersionNoByProCode(proCode,status,extType);
//    }
//
//    @Override
//    public List<InnerAgrt> selectInnerAgrt() {
//        return innerAgrtDao.selectInnerAgrt(wsFlowProcess.proxyVisibleProCodes());
//    }
//
//    @Override
//    public InnerAgrtDomain selectByInnerAgrtProCode(String proCode, String ids) {
//        return innerAgrtDao.selectByInnerAgrtProCode(proCode, ids);
//    }
//
//    @Override
//    public InnerAgrt selectInnerAgrtSignDate() {
//        return innerAgrtDao.selectInnerAgrtSignDate();
//    }
//
//    @Override
//    public InnerAgrt selectByProCodeAndId(String ids, String proCode) {
//        return innerAgrtDao.selectByProCodeAndId(ids, proCode);
//    }
//
//    @Override
//    public InnerAgrt selectByProCodes(String proCode) {
//        return innerAgrtDao.selectByProCodes(proCode);
//    }
//
//    @Override
//    public InnerAgrtDomain queryById(String id) {
//        return innerAgrtDao.selectById(id);
//    }
//
//    @Override
//    public InnerAgrt selectVersionByProCode(String proCode) {
//        return innerAgrtDao.selectVersionByProCode(proCode);
//    }
//
//    @Override
//    public int countByName(String names) {
//        return innerAgrtDao.countByName(names);
//    }
//
//    @Override
//    public InnerAgrtDomain selectByIds(String id) {
//        return innerAgrtDao.selectById(id);
//    }
//
////    @Override
////    @Transactional(rollbackFor = Exception.class)
////    public void sign(InnerAgrtVo innerAgrtVo, List<InnerAgrtAtt> innerAgrtAtts) {
////        InnerAgrt innerAgrt = new InnerAgrt();
////        innerAgrt.setId(innerAgrtVo.getId());
////        innerAgrt.setSignDate(innerAgrtVo.getSignDate());
////        innerAgrt.setUptBy(SessionUserUtils.getSessionUserId());
////        innerAgrt.setUptTime(DateUtils.getCurrentDateTime());
////        //更新记录
////        innerAgrtDao.updateByIdSelective(innerAgrt);
////
////        //添加附件
////        if(CollectionUtils.isNotEmpty(innerAgrtAtts)){
////            innerAgrtAttDao.insertByBatch(innerAgrtAtts);
////        }
////
////    }
//
//    @Override
//    public InnerAgrtVo queryByIds(String id) {
//        return innerAgrtDao.queryById(id);
//    }
//
//    @Override
//    public Page<BpastPackDeviceDomain> selectBpastByDomainWhere(Page<BpastPackDeviceDomain> page,
//                                                                String type, String orgId,
//                                                                String proName, String extType,
//                                                                String contractName) {
//        PageHelper.startPage(page.getPageNum(), page.getPageSize());
//        Map<String, Object> where = new HashMap<String, Object>();
//        where.put("proName", proName);
//        where.put("contractName", contractName);
//        where.put("extType", extType);
//        if(type.equals("2")){//区域公司
//            where.put("hrOrgAreaId", orgId);
//        }else if(type.equals("3")){//项目公司
//            where.put("hrOrgProId", orgId);
//        }
//        return (Page<BpastPackDeviceDomain>)innerAgrtDao.selectBpastByDomainWhere(where);
//    }
//
//    @Override
//    public List<InnerAgrt> isExistProName(String proCode) {
//        return innerAgrtDao.isExistProName(proCode);
//    }
}
